<?php
define("IN_DTE", true);

class Template {

	var $reuse_code = true;
	var $tpl_file; 
	var $cpl_file;
	var $data = array();
	var $parser;
	
	function Template ($template_filename = '') {
		global $tpl;
		$this->temp_dir = $tpl['compile_dir'];
		$this->isCompile = $tpl['parser_mode'];
		$this->cache_lifetime = '0';
		$this->template_dir = $tpl['tpl_dir'];
		$this->tpl_file = $template_filename;
	} 
	function assign ($name, $value = '') {
		if (is_array($name)) {
			foreach ($name as $k => $v) {
				$this->data[$k] = $v;
			} 
		} else {
			$this->data[$name] = $value;
		} 
	} 

	function result ($_top = '') {
		ob_start();
		$this->output($_top);
		$result = ob_get_contents();
		ob_end_clean();
		return $result;
	} 
	function output ($_top = '') {
		global $_top;
		if (strlen($this->template_dir) && substr($this->template_dir, -1) != '/') {
			$this->template_dir .= '/';
		} 
		if (strlen($this->temp_dir) && substr($this->temp_dir, -1) != '/') {
			$this->temp_dir .= '/';
		} 
		if (!is_array($_top)) {
			if (strlen($_top)) {
				$this->tpl_file = $_top;
			} 
			$_top = $this->data;
		} 

		$_obj = &$_top;
		$_stack_cnt = 0;
		$_stack[$_stack_cnt++] = $_obj;	
		$this->cpl_file = $this->temp_dir . preg_replace('/[:\/.\\\\]/', '_', $this->tpl_file) . '.php'; 
		$compile_template = true;
		if ($this->reuse_code) {
			if (is_file($this->cpl_file)){
				if ($this->cache_lifetime == '0'){
					$compile_template = true;
				} else {
						if ($this->mtime($this->cpl_file) > $this->mtime($this->template_dir . $this->tpl_file)) {
						$compile_template = false;
					} 
				} 
			} 
		} 
		if ($compile_template) {
			include_once ("TemplateParser.php");
			$this->parser = new TemplateParser($this->template_dir . $this->tpl_file);
			if (!$this->parser->compile($this->cpl_file, $this->isCompile)) {
				$this->Halt("编译模板 " . $this->parser->error . "时发生错误!");
			} 
		} 
		include($this->cpl_file);
		unset ($GLOBALS["_top"]);
	} 

	function mtime ($filename) {
		if (@is_file($filename)) {
			return filemtime($filename);
		} 
	} 

	function error($msg, $url = 'javascript:history.go(-1);', $page = "Tpl.php", $title = '编译模板时发生错误') {
		require_once(CLASS_PATH . 'Exception/' . $page);
		exit();
	} 
} 

?>
